/**
 * 评论组件 连接 form 与 list 两个控件
 */
define('components/Comment/Comment', [
    'components/Comment/com-xcomment.css',
    'components/Comment/XCommentForm',
    'components/Comment/XCommentList',
    'components/Page/Page',
    'utils/fetchEnhancer',
    'utils/Client',
    'utils/helpers'], function(css, XCommentForm, XCommentList, Page, fetch, Client, helpers){

function Comment(configs) {
    this.doc = document;

    this.container = null;
    this.commentForm = null;
    this.commentList = null;

    this.page = null;

    this.configs = {
        pageConfig: null,
        projectId: 0,
        postId: 0,
        isLogin: false,
        onLogin: null,
        formAvatar: ''
    };

    this.isPosting = false;
    this.cachedListData = null;

    this.init(configs);
}
Comment.prototype = {
    constructor: Comment,
    init: function(configs) {
        var _self = this;

        // configs
        if(undefined !== configs) {
            for(var k in configs) {
                this.configs[k] = configs[k];
            }
        }

        // form
        this.commentForm = new XCommentForm({
            isLogin: this.configs.isLogin,
            avatar: this.configs.formAvatar,
            onLogin: function() {
                _self.login();
            },
            onSubmit: function(v) {
                _self.postComment(v);
            }
        });

        // list
        this.commentList = new XCommentList({
            isLogin: this.configs.isLogin,
            formAvatar: this.configs.formAvatar,
            onReport: function(id) {
                console.log('reply', id);
            },
            onReply: function(id, v) {
                _self.postReply(id, v);
            },
            onLike: function(isLiked, id) {
                console.log(isLiked, id);
            },
            onLogin: function() {
                _self.login();
            },
            onLoadMoreReplies: function(pid, lastId) {
                _self.fetchReplies(pid, lastId);
            }
        });
    },
    login: function() {
        if(null !== this.configs.onLogin) {
            this.configs.onLogin();
        }
    },
    postReply: function(id, v) {
        var _self = this;

        if(!id || !v) {
            return;
        }

        this.postComment(v, id);
    },
    postComment: function(v, pid) {
        var _self = this;

        v = helpers.filterTags(v);

        if(!v) {
            XUI.toast.error('请输入内容');
            return;
        }

        if(this.isPosting) {
            return;
        }
        this.isPosting = true;

        var ret = {
            project_id: this.configs.projectId,
            parent_id: pid || '0',
            post_id: this.configs.postId,
            user_agent: Client.getClientSequence(),
            data: v
        };

        fetch('/api/comment/add', {
            method: 'POST',
            body: helpers.json2Query(ret)

        }).then(function(rs){
            _self.isPosting = false;

            if(0 === rs.status) {
                _self.commentForm.clear();

                _self.fetchList(1);
                return;
            }

            XUI.toast.error('服务器出错了 ' + rs.status);
        });
    },
    fetchList: function(page) {
        var _self = this;
        fetch('/api/comment/list?project_id='+ this.configs.projectId +'&page=' + page + '&postid=' + this.configs.postId).then(function(json){
            if(0 === json.status) {
                // 缓存一份
                _self.cachedListData = json.data;

                _self.commentList.renderList({
                    comments: json.data.data
                });

                _self.renderPage(json.data.total, json.data.page_size, json.data.current);
            }
        });
    },
    fetchReplies: function(pid, lastId) {
        var _self = this;
        fetch('/api/comment/replies?pid='+ pid +'&last_id=' + lastId).then(function(json){
            if(0 === json.status && _self.cachedListData) {
                var newList = json.data.data || [];
                var list = _self.cachedListData.data;

                for(var i=0; i<list.length; i++) {
                    if(String(list[i].id) !== pid) {
                        continue;
                    }

                    list[i].has_more_replies = json.data.has_more_replies;
                    list[i].replies = list[i].replies.concat(newList);
                }

                // 重新渲染
                _self.commentList.renderList({
                    comments: list
                });

                _self.renderPage(_self.cachedListData.total, _self.cachedListData.page_size, _self.cachedListData.current);
            }
        });
    },
    renderPage: function(total, pageSize, currentPage) {
        var _self = this;

        // 每提交一次 totla 就变了 所以重新初始化
        this.page = new Page(total, pageSize);
        if(this.configs.pageConfig) {
            for(var k in this.configs.pageConfig) {
                this.page.setConfig(k, this.configs.pageConfig[k]);
            }
        }
        this.page.onChange = function(p) {
            _self.fetchList(p);
        };

        this.page.currentPage = parseInt(currentPage, 10);
        this.page.render(this.commentList.pageWrapper);
    },
    render: function(containerId) {
        if(null === this.container) {
            this.container = this.doc.getElementById(containerId);
        }

        this.container.appendChild(this.commentForm.getDom());
        this.container.appendChild(this.commentList.getDom());

        this.fetchList(1);
    }
};

return Comment;
});
